import 'package:fish_redux/fish_redux.dart';
import 'package:flutter/material.dart' hide Action;
import 'package:fluttertoast/fluttertoast.dart';
import 'package:member_center_sdk/sdk.dart';
import 'package:member_center_sdk_example/pages/members/login/action.dart';
import 'package:member_center_sdk_example/pages/members/register/step1/page.dart';
import 'action.dart';
import 'state.dart';

Effect<PwdLoginState> buildEffect() {
  return combineEffects(<Object, Effect<PwdLoginState>>{
    PwdLoginAction.login: _onLoginAction,
    PwdLoginAction.register: _onRegisterAction,
    PwdLoginAction.switchLogin: _onSwitchAction,
  });
}

Future _onLoginAction(Action action, Context<PwdLoginState> ctx) async {
  var sdk = MemberCenterSdk.get();
  String userName = ctx.state.userNameController.text;
  String password = ctx.state.passwordController.text;
  if (userName.isEmpty) {
    Fluttertoast.showToast(msg: "请填写用户名");
    return;
  }
  if (password.isEmpty) {
    Fluttertoast.showToast(msg: "请填写密码");
    return;
  }
  ctx.dispatch(PwdLoginActionCreator.onLoadingAction(true));
  var grpcResult = await sdk.pwdAuth(1, userName, password);
  ctx.dispatch(PwdLoginActionCreator.onLoadingAction(false));
  if (!grpcResult.success) {
    Fluttertoast.showToast(msg: grpcResult.message);
  } else {
    Fluttertoast.showToast(msg: "登录成功");
    Navigator.of(ctx.context).pop(true);
  }
}

Future _onRegisterAction(Action action, Context<PwdLoginState> ctx) async {
  String userName = ctx.state.userNameController.text;
  var route = MaterialPageRoute(
    builder: (BuildContext buildCtx) => RegisterStep1Page().buildPage(userName),
  );
  var registerResult = await Navigator.of(ctx.context).push(route);
}

void _onSwitchAction(Action action, Context<PwdLoginState> ctx) {
  ctx.dispatch(MemberLoginActionCreator.onSmsLoginAction());
}
